<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/5/9 0009
 * Time: 下午 3:35
 */
namespace  Admin\Controller;

class MessageController extends AdminController{

    //消息管理首页
    public function index(){
        $keyword = I('keyword','','addslashes');
        $where = [];
        if(!empty($keyword)){
            $where['A.title'] = array('like', "%{$keyword}%");
            $where['A.content'] = array('like', "%{$keyword}%");
            $where['_logic'] = 'OR';
        }

        $count = M('Message')->alias('A')->where($where)->count();
        $Page = new \Think\Page($count);

        $messages = M('Message')->alias('A')->join(C('DB_PREFIX').'user B ON A.user_id = B.id','left')
            ->field('A.*,B.nickname')
            ->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('messages', $messages);
        $this->assign('page', $Page->show());
        $this->display();
    }

    //发送系统消息
    public function send(){
        if(IS_POST){
            $message = I('message','','addslashes');
            $title = I('title','','addslashes');
            if(empty($message)){
                $this->error('请输入消息内容');
            }
            if(empty($title)){
                $title = '系统消息';
            }
            //获取所有用户
            $where = [
                'status'=> 1,
                'freeze'=>0,
            ];

            $users = M('User')->where($where)->select();
            if(!empty($users)){
                $msg = [
                    'title' =>  $title,
                    'content' =>   $message,
                    'add_time'  =>  time(),
                ];
                foreach ($users as $k=>$v){
                    $msg['user_id'] = $v['id'];
                    M('Message')->data($msg)->add();
                }
                $this->success('系统消息发送成功');
                //发送消息
            }
            $this->error('没有可以发送消息的用户');
        }else{
            $this->display();
        }
    }

    public function view(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $this->error('参数错误');
        }
        $msg = M('Message')->find($id);
        if(empty($msg)){
            $this->error('没有找到消息');
        }else{
            $msg['user'] = M('User')->find($msg['user_id']);
            $msg['sender'] = M('User')->find($msg['f_user_id']);
        }
        $this->assign('msg', $msg);
        $this->display();
    }

    public function delete() {
        $id = I('id');
        if (!is_array($id)) {
            $id = [$id];
        }

        if(empty($id)){
            $this->error('没有选择要删除的项');
        }
        M('Message')->where(['id' => ['in', $id]])->delete();
        $this->success('删除成功');
    }
}